package com.huhao.smark;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.Locale;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import static com.huhao.smark.Config.*;

public class DetailFragment extends Fragment {

    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private TextView tvIncome, tvExpense, tvBalance;
    private Button btnFilterDate, btnFilterType, btnAddRecord;

    private TransactionAdapter adapter;
    private List<Transaction> transactions = new ArrayList<>();
    private List<Transaction> allTransactions = new ArrayList<>();
    private final DecimalFormat decimalFormat = new DecimalFormat("#,##0.00");

    private int currentYear;
    private int currentMonth;
    private int currentDay = 0; // 0 表示不筛选具体日
    private boolean[] currentTypeFilter = {true, true}; // 收入, 支出

    private ActivityResultLauncher<Intent> addRecordLauncher;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_detail, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initViews(view);
        checkLoginStatus();
        setupRecyclerView();
        swipeRefreshLayout.setOnRefreshListener(this::loadData);

        addRecordLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == requireActivity().RESULT_OK) {
                        loadData();
                        updateTransactionCount(); // 添加账目后更新计数
                    }
                }
        );

        btnAddRecord.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), AddRecordActivity.class);
            addRecordLauncher.launch(intent);
        });

        btnFilterDate.setOnClickListener(v -> showDateFilterDialog());
        btnFilterType.setOnClickListener(v -> showTypeFilterDialog());

        Calendar calendar = Calendar.getInstance();
        currentYear = calendar.get(Calendar.YEAR);
        currentMonth = calendar.get(Calendar.MONTH) + 1;

        if(isUserLoggedIn()){
            loadData();
        }
    }

    private void checkLoginStatus(){
        if(isUserLoggedIn()){
            // 用户已登录，显示正常内容
        }else{
            showUnauthenticatedContent();
        }
    }

    private boolean isUserLoggedIn(){
        SharedPreferences prefs = requireActivity().getSharedPreferences("app_prefs", Context.MODE_PRIVATE);
        return prefs.getBoolean("isLoggedIn", false);
    }

    private void showUnauthenticatedContent(){
        recyclerView.setVisibility(View.GONE);
        tvIncome.setVisibility(View.GONE);
        tvExpense.setVisibility(View.GONE);
        tvBalance.setVisibility(View.GONE);
        btnFilterDate.setVisibility(View.GONE);
        btnFilterType.setVisibility(View.GONE);
        btnAddRecord.setVisibility(View.GONE);
        Toast.makeText(getContext(), "您未登录，请先登录", Toast.LENGTH_SHORT).show();
    }

    private void initViews(View view) {
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        recyclerView = view.findViewById(R.id.rv_transactions);
        tvIncome = view.findViewById(R.id.tv_income);
        tvExpense = view.findViewById(R.id.tv_expense);
        tvBalance = view.findViewById(R.id.tv_balance);
        btnFilterDate = view.findViewById(R.id.btn_filter_date);
        btnFilterType = view.findViewById(R.id.btn_filter_type);
        btnAddRecord = view.findViewById(R.id.btn_add_record);
    }

    private void setupRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new TransactionAdapter(transactions);
        recyclerView.setAdapter(adapter);
    }

    private void loadData() {
        swipeRefreshLayout.setRefreshing(true);
        updateDateButtonText();
        SharedPreferences prefs = requireActivity().getSharedPreferences("app_prefs", Context.MODE_PRIVATE);
        String token = prefs.getString("token", "");

        if (token.isEmpty()) {
            Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
            swipeRefreshLayout.setRefreshing(false);
            return;
        }

        String url = BASE_URL + ADD_RECORD +
                "?year=" + currentYear +
                "&month=" + currentMonth;

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                requireActivity().runOnUiThread(() -> {
                    swipeRefreshLayout.setRefreshing(false);
                    Toast.makeText(getContext(), "加载失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseData = response.body().string();
                requireActivity().runOnUiThread(() -> {
                    swipeRefreshLayout.setRefreshing(false);
                    try {
                        if (response.isSuccessful()) {
                            parseResponseData(responseData);
                        } else {
                            Toast.makeText(getContext(), "请求失败: " + response.code(), Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        Toast.makeText(getContext(), "解析数据失败", Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                });
            }
        });
    }

    private void parseResponseData(String responseData) throws JSONException {
        JSONObject json = new JSONObject(responseData);
        if (json.getBoolean("success")) {
            JSONArray data = json.getJSONArray("data");
            allTransactions.clear();
            for (int i = 0; i < data.length(); i++) {
                JSONObject item = data.getJSONObject(i);
                int type = item.getInt("type");
                double amount = item.getDouble("price");
                Transaction transaction = new Transaction(
                        item.getInt("id"),
                        type == 0 ? "income" : "expense",
                        item.getString("category"),
                        amount,
                        item.getString("remark"),
                        item.getString("bookDate")
                );
                allTransactions.add(transaction);
            }
            applyFilters();
        } else {
            Toast.makeText(getContext(), "获取数据失败: " + json.getString("message"), Toast.LENGTH_SHORT).show();
        }
    }

    private void showDateFilterDialog() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        if (currentYear != 0 && currentMonth != 0) {
            year = currentYear;
            month = currentMonth - 1;
            day = currentDay == 0 ? day : currentDay;
        }

        DatePickerDialog datePickerDialog = new DatePickerDialog(
                requireContext(),
                (view, selectedYear, selectedMonth, selectedDay) -> {
                    currentYear = selectedYear;
                    currentMonth = selectedMonth + 1;
                    currentDay = selectedDay;
                    applyFilters();
                    if(isUserLoggedIn()){
                        loadData();
                    }
                    updateDateButtonText();
                },
                year, month, day
        );

        datePickerDialog.setButton(DatePickerDialog.BUTTON_NEUTRAL, "清除", (dialog, which) -> {
            Calendar cal = Calendar.getInstance();
            currentYear = cal.get(Calendar.YEAR);
            currentMonth = cal.get(Calendar.MONTH) + 1;
            currentDay = 0;
            if(isUserLoggedIn()){
                applyFilters();
                loadData();
            }
            updateDateButtonText();
        });

        datePickerDialog.setTitle("选择日期");
        datePickerDialog.show();
    }

    private void updateDateButtonText() {
        if (currentDay != 0) {
            btnFilterDate.setText(String.format(Locale.getDefault(),
                    "%d年%d月%d日", currentYear, currentMonth, currentDay));
        } else {
            btnFilterDate.setText(String.format(Locale.getDefault(),
                    "%d年%d月", currentYear, currentMonth));
        }
    }

    private void showTypeFilterDialog() {
        final String[] filterOptions = {"收入", "支出"};
        final boolean[] checkedItems = currentTypeFilter.clone();

        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("选择类型")
                .setPositiveButton("确定", (dialog, which) -> {
                    currentTypeFilter = checkedItems;
                    if(isUserLoggedIn()){
                        applyFilters();
                        loadData();
                    }
                    updateTypeButtonText();
                })
                .setNegativeButton("取消", null)
                .setMultiChoiceItems(filterOptions, checkedItems, (dialog, which, isChecked) -> {
                    checkedItems[which] = isChecked;
                });

        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void updateTypeButtonText() {
        if (currentTypeFilter[0] && currentTypeFilter[1]) {
            btnFilterType.setText("类型筛选：全部");
        } else if (currentTypeFilter[0]) {
            btnFilterType.setText("类型筛选：收入");
        } else if (currentTypeFilter[1]) {
            btnFilterType.setText("类型筛选：支出");
        } else {
            btnFilterType.setText("类型筛选：全部");
        }
    }

    private void applyFilters() {
        List<Transaction> filtered = filterTransactionsByDate(allTransactions);
        filtered = filterTransactionsByType(filtered, currentTypeFilter);
        transactions.clear();
        transactions.addAll(filtered);
        calculateTotals();
        adapter.notifyDataSetChanged();
    }

    private List<Transaction> filterTransactionsByDate(List<Transaction> source) {
        if (currentDay == 0) {
            return new ArrayList<>(source);
        }

        List<Transaction> result = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

        for (Transaction t : source) {
            try {
                Date recordDate = sdf.parse(t.getRecordDate());
                Calendar cal = Calendar.getInstance();
                cal.setTime(recordDate);

                if (cal.get(Calendar.YEAR) == currentYear &&
                        cal.get(Calendar.MONTH) + 1 == currentMonth &&
                        cal.get(Calendar.DAY_OF_MONTH) == currentDay) {
                    result.add(t);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    private List<Transaction> filterTransactionsByType(List<Transaction> source, boolean[] checkedItems) {
        List<Transaction> result = new ArrayList<>();
        for (Transaction transaction : source) {
            boolean isIncome = "income".equals(transaction.getType());
            if ((checkedItems[0] && isIncome) ||
                    (checkedItems[1] && !isIncome)) {
                result.add(transaction);
            }
        }
        return result;
    }

    private void calculateTotals() {
        double totalIncome = 0;
        double totalExpense = 0;

        for (Transaction t : transactions) {
            if ("income".equals(t.getType())) {
                totalIncome += t.getAmount();
            } else {
                totalExpense += t.getAmount();
            }
        }

        double balance = totalIncome - totalExpense;

        tvIncome.setText("¥" + decimalFormat.format(totalIncome));
        tvExpense.setText("¥" + decimalFormat.format(totalExpense));
        tvBalance.setText("¥" + decimalFormat.format(balance));
    }

    private void updateTransactionCount() {
        SharedPreferences prefs = requireActivity().getSharedPreferences("app_prefs", Context.MODE_PRIVATE);
        String account = prefs.getString("account", "");

        if (account.isEmpty()) {
            return; // 静默处理
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        String currentDate = sdf.format(new Date());
        String fileName = account + ".json";
        File externalDir = requireContext().getExternalFilesDir(null); // 获取外部存储目录
        File externalFile = new File(externalDir, fileName);

        try {
            JSONObject json;
            // 1. 如果文件存在直接读取
            if (externalFile.exists()) {
                json = readJsonFromFile(externalFile);
            }
            // 2. 文件不存在时创建新JSON对象
            else {
                json = new JSONObject();
            }
            // 更新计数
            int count = json.optInt(currentDate, 0);
            json.put(currentDate, count + 1);
            // 保存更新
            saveJsonToFile(externalFile, json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private JSONObject readJsonFromFile(File file) throws IOException, JSONException {
        FileInputStream fis = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader reader = new BufferedReader(isr);

        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }

        reader.close();
        return new JSONObject(sb.toString());
    }

    private void saveJsonToFile(File file, JSONObject json) throws IOException {
        FileOutputStream fos = new FileOutputStream(file);
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        osw.write(json.toString());
        osw.flush();
        osw.close();
    }

    private class TransactionAdapter extends RecyclerView.Adapter<TransactionAdapter.ViewHolder> {

        private final List<Transaction> transactions;

        public TransactionAdapter(List<Transaction> transactions) {
            this.transactions = transactions;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_transaction, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            Transaction transaction = transactions.get(position);
            holder.bind(transaction);
        }

        @Override
        public int getItemCount() {
            return transactions.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            private final TextView tvCategory;
            private final TextView tvAmount;
            private final TextView tvDescription;
            private final TextView tvDate;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                tvCategory = itemView.findViewById(R.id.tv_category);
                tvAmount = itemView.findViewById(R.id.tv_amount);
                tvDescription = itemView.findViewById(R.id.tv_description);
                tvDate = itemView.findViewById(R.id.tv_date);

                itemView.setOnClickListener(v -> {
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        Transaction transaction = transactions.get(position);
                        Intent intent = new Intent(itemView.getContext(), DetailActivity.class);
                        intent.putExtra("recordId", transaction.getId());
                        itemView.getContext().startActivity(intent);
                    }
                });
            }

            public void bind(Transaction transaction) {
                tvCategory.setText(transaction.getCategory());
                tvDescription.setText(transaction.getDescription());

                String amountText = (transaction.getType().equals("expense") ? "-" : "+")
                        + "¥" + String.format(Locale.getDefault(), "%.2f", transaction.getAmount());
                tvAmount.setText(amountText);

                int colorResId = transaction.getType().equals("expense") ? R.color.red : R.color.green;
                int color = itemView.getContext().getResources().getColor(colorResId, null);
                tvAmount.setTextColor(color);

                try {
                    SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
                    Date date = inputFormat.parse(transaction.getRecordDate());
                    SimpleDateFormat outputFormat = new SimpleDateFormat("MM/dd", Locale.getDefault());
                    tvDate.setText(outputFormat.format(date));
                } catch (Exception e) {
                    tvDate.setText(transaction.getRecordDate());
                }
            }
        }
    }

    private static class Transaction {
        private final int id;
        private final String type;
        private final String category;
        private final double amount;
        private final String description;
        private final String recordDate;

        public Transaction(int id, String type, String category, double amount,
                           String description, String recordDate) {
            this.id = id;
            this.type = type;
            this.category = category;
            this.amount = amount;
            this.description = description;
            this.recordDate = recordDate;
        }

        public int getId() { return id; }
        public String getType() { return type; }
        public String getCategory() { return category; }
        public double getAmount() { return amount; }
        public String getDescription() { return description; }
        public String getRecordDate() { return recordDate; }
    }
}